<template>
	<view>
		<!-- 收货地址 -->
		<view class="addr" @tap="selectAddress">
			<view class="icon">
				<image src="../../static/img/addricon.png" mode=""></image>
			</view>
			<view class="right" v-if="defaultAddress">
				<view class="tel-name">
					<view class="name">
						{{defaultAddress.consignee}}
					</view>
					<view class="tel">
						{{defaultAddress.mobile}}
					</view>
				</view>
				<view class="addres">
					{{defaultAddress.allAddress}}
				</view>
			</view>
			<view class="right" v-if="!defaultAddress" style="display: flex; justify-content: center; align-items: center;color:#E80505;">
				<span style="margin-right: 0px;">您还未添加收货地址，快去添加吧。</span><span class="icon">&#xe62d;</span>
			</view>
		</view>
		<!-- 购买商品列表 -->
		<view class="buy-list">
			<order-card
				v-for="(item, index) in orderInfo"
				:orderInfo="item"
				:key="index"
				:check="check"
				:deliveries="deliveries"
				:index="index"
				@countPrice="countPrice"
			>
			</order-card>
		</view>
		<view class="footer"  v-if="!check">
			<view class="settlement">
				<view class="sum">合计:<view class="money">￥{{sumPrice|toFixed}}</view></view>
				<view class="btn" @tap="toPay()">提交订单</view>
			</view>
		</view>
		<view class="footer" v-else>
			<view class="action-box b-t" v-if="orderInfo[0].orderStatus != 99 ">
				<!-- 待支付的订单 -->
				<button class="action-btn" v-if="orderInfo[0].orderStatus === '0' " @click.stop="deleteOrder(orderInfo[0])">取消订单</button>
				<button class="action-btn recom" v-if="orderInfo[0].orderStatus === '0'" @click.stop="pay(orderInfo[0])">{{orderInfo[0].payStatus === '0'? '立即支付': '重新支付'}}</button>
				<!-- 待发货的订单 无按钮-->
				<!-- 待收获的订单 -->
				<button class="action-btn recom" v-if="orderInfo[0].orderStatus === '2'" @click.stop="configReceipt(orderInfo[0])">确认收货</button>
				<!-- 待评价的订单 -->
				<button class="action-btn recom" v-if="orderInfo[0].orderStatus === '3'" @click.stop="evaluate(orderInfo[0])">评价</button>
				<!-- 已完成的订单  查看评价-->
				<button class="action-btn recom" v-if="orderInfo[0].orderStatus === '4'" @click.stop="comment(orderInfo[0])">查看评价</button>
				<!-- 退款售后的订单 无按钮-->
			</view>
		</view>
		<popup-layer ref="popupRef" :direction="'top'" v-model="boolShow">
			<view class="replacement_box" >
				<view class="replacement_box_title">取消理由</view>
				 <scroll-view 
					scroll-top="0"
					scroll-y="true"
					style="height: 100%;"
				>
					<view class="replacement_box_item" v-for="(item, index) in reasons" :key="index">
							<view class="replacement_box_text">{{item.title}}</view>
						<!-- checkbox --> 
						<view class="checkbox-box" @tap="selected(item.value)">
							<view class="checkbox">
								<view :class="[reason === item.value ? 'on' : '']"></view>
							</view>
						</view>
					</view>
					<view class="replacement_box_item" style="margin: 20px">
						<view class="replacement_box_text">取消理由</view>
						<view class="replacement_box_right">
							<input placeholder="请留下您宝贵的建议" v-model="CancelReasonStr"/>
						</view>
					</view>
				</scroll-view>
				<button type="primary" class="feedback-submit replacement_button" @tap="confirmDelete(item)" >完成</button>
			</view>
		</popup-layer>			
		<uni-fab ref="fab" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical" :direction="direction" @trigger="trigger" />
	</view>
</template>

<script>
	import {  
		mapState,
		mapActions
	} from 'vuex';  
	import orderApis from '@/common/services/order.js';
	import addressApis from '@/common/services/address.js'
	import otherApis from '@/common/services/other.js';
	import orderCard from '@/components/order-info/order-info.vue'
	import popupLayer from '@/components/popup-layer/popup-layer.vue';
	import uniFab from '@/components/uni-fab/uni-fab.vue'
	import shopCartApis from '@/common/services/shopCart.js'
	export default {
		data() {
			return {
				goodsPrice:0.0,	//商品合计价格
				sumPrice:0.0,	//用户付款价格
				// leaveMsg: [],		//备注 客户留言
				defaultAddress: {}, // 默认地址 如果默认地址为空，需要提示用户添加默认地址
				deliveries: [],
				currentIndex: 0,
				check: false ,// 是订单查询 true 还是提交订单页面 false
				boolShow:false,
				CancelReasonStr: '',
				reasons: [],
				reason: '',
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#A2313E',
					buttonColor: 'rgb(0,0,0)'
				},
				content: [
					{
						iconPath: "/static/icon/chat.png",
						selectedIconPath: "/static/icon/chat1.png",
						text: '联系客服',
						active: false
					},
					{
						iconPath: "/static/icon/home.png",
						selectedIconPath: "/static/icon/home1.png",
						text: '首页',
						active: false
					},
					{
						iconPath: "/static/icon/type.png",
						selectedIconPath: "/static/icon/type1.png",
						text: '分类',
						active: false
					},
					{
						iconPath: "/static/icon/shopCart.png",
						selectedIconPath: "/static/icon/shopCart1.png",
						text: '购物车',
						active: false
					}
				],
			};
		},
		components:{
			orderCard,
			popupLayer,
			uniFab
		},
		computed: {
		 	...mapState(['orderInfo']),
		},
		filters: {
			toFixed:function(x) {
				return parseFloat(x).toFixed(2);
			},
			formatUrl: function(url) {
				return url && url.indexOf('http') !== -1 ? url : 'http://106.13.76.109:8080/xsmall/sys/common/view/'+ url
			}
		},
		onLoad(option) {
			otherApis.getUnicode('cancel_reason').then(res => {
				this.reasons = res;
			})
			orderApis.getShipping().then(res => {
				this.deliveries = res;
				let orderInfo;
				//页面显示时，加载订单信息
				orderInfo = this.orderInfo.map(item => {
					if (option.orderId) {
						this.check = true;
					} else {
						let {id, insure, shippingName} = this.deliveries[0];
						item.shippingId = id;
						item.insure = insure;
						item.shippingName = shippingName;
						item.isnoInv = '0';
					}
					return item
				})
				this.setOrderInfo({ orderInfo })
				this.countPrice(orderInfo);
			})
		},
		onShow() {
			// 获取用户的默认地址 defaultAddress 存储在本地
			addressApis.getDefaultAddress().then(res => {
				this.defaultAddress = res;
			})
		},
		onHide() {
		},
		onBackPress() {
			//页面后退时候，清除订单信息
			this.clearOrder();
		},
		methods: {
			trigger(e) {
				switch (e.index){
					case 0:
						uni.navigateTo({
							url: '../chat/chat',
						})
						break;
					case 1:
						uni.reLaunch({
							url: '../home/index',
							animationType: 'pop-in',
							animationDuration: 200
						});
						break;
					case 2:
						uni.reLaunch({
							url: '../class/index',
						});
						break;
					case 3:
						uni.reLaunch({
							url: '../shopCart/shopCart',
						});
						break;
					default:
						break;
				}
			},
			selected(value) {
				this.reason = value;
			},
			clearOrder(){
				this.deleteOrderInfo()
			},
			toPay(){
				if(!this.defaultAddress || !this.defaultAddress.id) {
					uni.showToast({
						title:'收货地址不能为空！'	
					})
					return false;
				}
				uni.showLoading({
					title:'正在提交订单...'
				})
				let orderInfo = this.orderInfo.map(item => {
					item.goodsCount = item.goodsNumber;
					delete item.goodsNumber
					return item;
				})
				
				orderApis.creatOrder({
					userAddressId: this.defaultAddress.id,
					goodsList: orderInfo
				}).then(res => {
					let orderSn = ''
					let orderId = ''
					res.map((item, index) => {
						orderSn = orderSn + item.orderSn + (index !== res.length - 1 &&  res.length > 1 ? ',':'');
						orderId = orderId + item.orderId + (index !== res.length - 1 &&  res.length > 1 ? ',':'');
					})
		
					uni.hideLoading();
					uni.redirectTo({
						url:`../pay/payment/payment?orderId=${orderId}&amount=${this.sumPrice}&orderSn=${orderSn}`
					})
					// 如果是购物车中的商品 提交订单成功之后，需要清除购物车；
					if (this.check === false) {
						this.orderInfo.map(item => {
							shopCartApis.deleteShopCart(item.id).then(res => {
								console.log('购物车商品删除成功');
							})
						})
					}
				})
				
			},
			//选择收货地址
			selectAddress(){
				if (this.check) return false;
				uni.navigateTo({
					url:'../address/address?type=select'
				})
			},
			//取消订单
			deleteOrder(){
				// 需要弹出取消订单的理由 点击确认之后才能取消
				this.$refs.popupRef.show();
			},
			// 确认取消
			confirmDelete(){
				orderApis.cancelOrder(
					{orderId: this.orderInfo[0].orderId, CancelReasonStr: this.CancelReasonStr + this.reasons[this.reason].title},
				).then(res => {	
					this.$refs.popupRef.close();
				})
			},
			// 支付订单
			pay(item) {
				const sumPrice = item.goodsCount * item.goodsPrice + item.insure;
				uni.navigateTo({
					url: `../pay/payment/payment?amount=${sumPrice}&orderId=${item.orderId}`
				})
			},
			// 确认收货
			configReceipt(item) {
				orderApis.confirmReceive(item.orderId).then(res => {
					uni.showToast({
						icon: 'none',
						title: '收货成功',
					});	
					console.log('收货地址成功：', res);
					uni.navigateTo({
						url: '../myOrder/myOrder?state=3'
					})
				})
			},
			// 评价购物
			evaluate(item) {
				uni.navigateTo({
					url: `../publish/publish?${item.orderId}`
				})
			},
			// 查看评价
			comment(item) {
				uni.navigateTo({
					url: `../comment/comment?${item.orderId}`
				})
			},
			// 联系客服
			toChat(item) {
				uni.navigateTo({
					url: '../chat/chat'
				})
			},
			// 查看订单详情
			toOrder(id) {
				uni.navigateTo({
					url: `../order/confirmation?orderId=${id}`
				})
			},
			// 合计
			...mapActions({
				deleteOrderInfo: 'DELETE_ORDER_INFO',
				setOrderInfo: 'SET_ORDER_INFO'
			}),
			// 计算价格
			countPrice (orderInfo) {
				console.log('sjjsjs:', orderInfo)
				let goodsPrice = 0;
				//合计
				let len = orderInfo.length;
				for(let i=0;i<len;i++){
					goodsPrice = 
						goodsPrice
						+ orderInfo[i].goodsNumber*orderInfo[i].shopPrice 
						+ orderInfo[i].insure;
				}
				this.sumPrice = goodsPrice
			},
		}
	}
</script>

<style lang="scss" scoped>
page {
	background-color: white;
}
@font-face {
	font-family: 'iconfont';
	src: url('../../css/font/iconfont.eot');
	src: url('../../css/font/iconfont.eot?#iefix') format('embedded-opentype'),
	url('../../css/font/iconfont.woff') format('woff'),
	url('../../css/font/iconfont.ttf') format('truetype'),
	url('../../css/font/iconfont.svg#iconfont') format('svg');
}
.icon {
	font-family:"iconfont" !important;
	font-size: 26upx;
	font-weight: 200;
	font-style:normal;
	-webkit-font-smoothing: antialiased;
	-webkit-text-stroke-width: 0.2px;
	-moz-osx-font-smoothing: grayscale;
	cursor: pointer;
	color: #999;
	&:hover {
		color:linear-gradient( 135deg, #FDD819 10%, #E80505 100%);
	}
}
.addr{
	width: 86%;
	padding: 20upx 3%;
	margin: 30upx auto 20upx auto;
	box-shadow: 0upx 5upx 20upx rgba(0,0,0,0.1);
	border-radius: 20upx;
	display: flex;
	.icon{
		width: 80upx;
		height: 80upx;
		display: flex;
		align-items: center;
		image{
			width: 60upx;
			height: 60upx;
		}
	}
	.tel-name{
		width: 100%;
		display: flex;
		font-size: 32upx;
		.tel{
			margin-left: 40upx;
		}
	}
	.addres{
		width: 100%;
		font-size: 26upx;
		color: #999;
	}
}
.buy-list{
	margin: 30upx 0upx 120upx;
	width: 100%;
}

.blck{
	width: 100%;
	height: 100upx;
}
.footer{
		width: 92%;
		padding: 0 4%;
		background-color: #fbfbfb;
		height: 100upx;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		font-size: 28upx;
		position: fixed;
		bottom: 0upx;
		z-index: 5;
		box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.2);
		.action-box{
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100upx;
			position: relative;
			padding-right: 30upx;
		}
		.action-btn{
			width: 160upx;
			height: 60upx;
			margin: 0;
			margin-left: 24upx;
			padding: 0;
			text-align: center;
			line-height: 60upx;
			font-size: $font-sm + 2upx;
			color: $font-color-dark;
			background: #fff;
			border-radius: 100px;
			&:after{
				border-radius: 100px;
			}
			&.recom{
				background: #fff9f9;
				color: $base-color;
				&:after{
					border-color: #f7bcc8;
				}
			}
		}
		.settlement{
			width: 80%;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			.sum{
				width: 50%;
				font-size: 28upx;
				margin-right: 10upx;
				display: flex;
				justify-content: flex-end;
				.money{
					font-weight: 600;
				}
			}
			.btn{
				padding: 0 30upx;
				height: 60upx;
				background-color: #E80505;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 30upx;
				border-radius: 40upx;
			}
		}
	}
	.replacement_box {
		width: 100%;
		height: 800upx;
		display: flex;
		flex-direction: column;
		padding: 0upx 20upx 180upx;;
		box-sizing: border-box;
		.feedback-submit {
			box-shadow: 0upx 5upx 10upx rgba(0,0,0,0.4);
			margin: 20upx auto;
			height: 80upx;
			background-color: #E80505;
			color: #fff;
			justify-content: center;
			align-items: center;
			&:hover {
				background-color: #862732;
			}
		 }
		.replacement_button {
			position: fixed;
			bottom: 0;
			width: 95%
		}
		.replacement_box_title {
			display: flex;
			align-items: center;
			font-size: 30upx;
			text-align: center;
			margin-top: 20upx;
			justify-content: center;
		}
		.replacement_box_item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid #ece7e7;
			padding: 20upx 0upx;
			&:last-child {
				border-bottom: 0px solid #ece7e7;
			}
			.replacement_box_right {
				color: #666;
				font-size: 26upx;
				display: flex;
				justify-content: flex-end;
				flex: 4;
				input {
					font-size: 26upx;
					width: 80%;
				}
			}
			.checkbox-box{
				display: flex;
				align-items: center;
				width: 30upx;
				height: 30upx;
				.checkbox{
					width: 30upx;
					height: 30upx;
					border-radius: 100%;
					border: solid 1upx #E80505;
					display: flex;
					align-items: center;
					justify-content: center;
					.on{
						width: 24upx;
						height: 24upx;
						border-radius: 100%;
						background-color: #E80505;
						align-self: center;
						justify-content: center;
					}
				}
				.text{
					font-size: 28upx;
					margin-left: 10upx;
				}
			}
		}
	}
</style>
